package com.javasm.service.JINXIAOService.impl;

import com.javasm.commons.basic.BaseServiceImpl;
import com.javasm.entity.JINXIAOEntity.SysDept;
import com.javasm.service.JINXIAOService.SysDeptService;
import com.javasm.dao.JINXIAODao.SysDeptDao;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SysDeptServiceImpl extends BaseServiceImpl<SysDeptDao, SysDept> implements SysDeptService {

     public List<SysDept> buildTree(List<SysDept> list, String root){
        List<SysDept> result = new ArrayList<>();
        for (SysDept sysDept : list) {
            String pid = sysDept.getPid();
            if(root.equals(pid)){
                String id = sysDept.getId();
                    List<SysDept> childs = buildTree(list, id);
                if(childs!=null && childs.size()>0){
                    sysDept.setChilds(childs);
                }
                result.add(sysDept);
            }
        }
        return result;
    }


    @Override
    public List<SysDept> deptTree(String deptName) {
        List<SysDept> sysDepts =null;
        if(deptName==null || deptName.equals("")){
            sysDepts = this.baseDao.queryAll(null);
        }else{
            List<String> ids1 = this.baseDao.queryIds(deptName);

            Set<String> ids = new HashSet<>();
            //筛选出sysDepts集合中的每个数据pid值.
            for (String id : ids1) {
                Set<String> allPids = getAllPids(id);
                ids.addAll(allPids);
            }
            //对pid进行两位截取,得到全部需要查询的部门id集合.
            sysDepts = this.baseDao.queryByIds(ids);
        }
        List<SysDept> result = buildTree(sysDepts, "-1");
        return result;
    }

    private Set<String> getAllPids(String id){
        Set<String> r = new HashSet<>();
        if(!id.equals("-1")){
            int length = id.length();
            int s = length/2;
            for(int i=1;i<=s;i++){
                r.add(id.substring(0,2*i));
            }
        }
        return r;
    }
    
}